<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card" style="margin-top: 10px">
      <el-row :gutter="20">
        <el-col :span="6"
          ><div class="grid-content bg-purple">
            <el-input
              placeholder="请输入内容"
              class="input-with-select"
              v-model="queryInfo.query"
              clearable
              @clear="getUserList"
            >
              <el-button
                slot="append"
                icon="el-icon-search"
                @click="getUserList"
              ></el-button>
            </el-input></div
        ></el-col>
        <el-col :span="6">
          <div class="grid-content bg-purple">
            <el-button type="primary" @click="dialogVisible = true"
              >添加用户</el-button
            >
          </div></el-col
        >
      </el-row>
      <el-table :data="users" stripe border style="width: 100%">
        <el-table-column type="index"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>

        <el-table-column label="状态">
          <template v-slot="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="changeStatus(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <!-- 通过作用域插槽来自定义操作做结构 -->
          <template v-slot="scopte">
            <!-- 编辑按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="modifyDialog(scopte.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="removeUser(scopte.row.id)"
            ></el-button>
            <!-- 提示 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button type="warning" icon="el-icon-setting" @click="setRoleDialogActive(scopte.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 3, 4]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="queryInfo.total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="30%"
      @close="closeForm"
    >
      <!-- 主题区 -->
      <el-form
        :model="addUser"
        :rules="userRules"
        ref="form"
        label-width="80px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUser.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUser.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUser.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addUser.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="checkForm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="addModifyDialog"
      width="30%"
      @close="resetModifyDialog"
    >
      <el-form
        ref="modifyUserRef"
        :model="modifyUser"
        label-width="70px"
        :rules="ModifyUserRules"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="modifyUser.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="modifyUser.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="modifyUser.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addModifyDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitModifyUser(modifyUser.id)"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="setRoleDialogVisible"
      width="30%"
      @close="closeSetRoleDialog"
    >
       <div><span>当前用户: </span><span>{{userInfor.username}}</span></div>
       <div><span>当前用户的角色: </span><span>{{userInfor.role_name}}</span></div>
        <p>分配新角色: <el-select v-model="selectValue" placeholder="请选择">
    <el-option
      v-for="item in roles"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
  </el-select></p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitSetRole"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data () {
    return {
      queryInfo: {
        query: '',
        // 当前页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 2
      },
      // 数据
      users: [],
      // 总共多少钱数据
      total: '',
      dialogVisible: false,
      // 添加用户数据
      addUser: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户规则
      ModifyUserRules: {
        username: [
          {
            required: true,
            trigger: 'blur',
            message: '用户名不能为空'
          },
          {
            min: 3,
            max: 10,
            trigger: 'blur',
            message: '用户名必须是3-10位'
          }
        ],
        password: [
          {
            required: true,
            trigger: 'blur',
            message: '密码不能为空'
          },
          {
            min: 6,
            max: 16,
            trigger: 'blur',
            message: '密码必须是6-16位'
          }
        ],
        email: [
          {
            required: true,
            trigger: 'blur',
            message: '邮箱不能为空'
          },
          {
            trigger: 'blur',
            pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
            message: '格式不对'
          }
        ],
        mobile: [
          {
            required: true,
            trigger: 'blur',
            message: '手机号不能为空'
          },
          {
            trigger: 'blur',
            pattern: /^[1-9]{1}[0-9]{10}$/,
            message: '格式不对'
          }
        ]
      },

      // 修改用户的规则
      userRules: {
        mobile: [
          {
            required: true,
            trigger: 'blur',
            message: '手机号不能为空'
          },
          {
            trigger: 'blur',
            pattern: /^[1-9]{1}[0-9]{10}$/,
            message: '格式不对'
          }
        ],
        email: [
          {
            required: true,
            trigger: 'blur',
            message: '邮箱不能为空'
          },
          {
            trigger: 'blur',
            pattern: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
            message: '格式不对'
          }
        ]
      },
      // 用户修改对话框的boolean值
      addModifyDialog: false,
      // 查询用户修改的数据
      modifyUser: {},
      // 分配角色对话框显示的boolean值
      setRoleDialogVisible: false,
      // 分配角色获取的数据
      userInfor: {},
      // 获取所有角色的数组
      roles: [],
      selectValue: ''
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    // 获取数据
    async getUserList () {
      const { data: res } = await this.$http.get('/users', {
        params: this.queryInfo
      })
      if (res.meta.status === 200) {
        const { users, total } = res.data
        console.log('aa')
        console.log(users)
        this.users = users
        this.total = total
      } else {
        return this.$message.error('请求失败')
      }
    },
    // 监听pagesize发生改变
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 页码值发生该变
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 改变状态
    async changeStatus (user) {
      console.log(user)
      const { data: res } = await this.$http.put(
        `users/${user.id}/state/${user.mg_state}`
      )
      if (res.meta.status === 200) {
        return this.$message.success('修改成功')
      } else {
        // 保证页面上的状态没有变化
        user.status = !user.status
        return this.$$message.error('修改失败')
      }
    },
    // 清空添加用户的表单
    closeForm () {
      this.$refs.form.resetFields()
    },
    // 添加用户的表单预验证
    checkForm () {
      console.log('AA')
      this.$refs.form
        .validate()
        .then(async () => {
          const { data: res } = await this.$http.post('/users', this.addUser)
          console.log(res)
          if (res.meta.status === 201) {
            this.getUserList()
            this.$message.success('添加成功')
            this.dialogVisible = false
          } else {
            this.$message.error('添加失败')
          }
        })
        .catch(() => {
          this.$message.error('表单验证失败')
        })
    },
    // 添加修改对话框
    async modifyDialog (id) {
      console.log(id)
      // 通过scope获取id渲染数据
      const { data: res } = await this.$http.put(`users/${id}`)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('查询数据失败')
      }
      this.modifyUser = res.data
      this.addModifyDialog = true
    },
    // 重置修改对话框
    resetModifyDialog () {
      this.$refs.modifyUserRef.resetFields()
    },
    // 提交用户表单修改
    async submitModifyUser (id) {
      this.$refs.modifyUserRef
        .validate()
        .then(async () => {
          // 发送网络请求
          const { data: res } = await this.$http.put(`users/${id}`, {
            email: this.modifyUser.email,
            mobile: this.modifyUser.mobile
          })
          console.log(this.modifyUser.email)
          console.log(res)
          // 判断
          if (res.meta.status !== 200) {
            return this.$message.error('提交失败')
          }
          // 关闭对话框
          this.addModifyDialog = false
          // 刷新数据
          this.getUserList()

          this.$message.success('修改成功')
        })
        .catch(() => {
          return this.$message.error('提交表单失败')
        })
    },
    // 删除用户
    removeUser (id) {
      console.log(id)
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          const { data: res } = await this.$http.delete(`users/${id}`)
          console.log(res)
          this.getUserList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 显示分配角色的对话框
    async setRoleDialogActive (role) {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取失败')
      }
      this.userInfor = role
      this.roles = res.data

      this.setRoleDialogVisible = true
    },
    // 提交分配角色方法
    async submitSetRole () {
      const { data: res } = await this.$http.put(`users/${this.userInfor.id}/role`, {
        rid: this.selectValue
      })
      console.log(res)
      if (res.meta.status !== 200 || this.selectValue === '') {
        return this.$message.error('提交失败')
      }
      this.$message.success('修改成功')
      this.getUserList()
      this.setRoleDialogVisible = false
    },
    // 关闭对话框重置选择数据
    closeSetRoleDialog () {
      this.selectValue = ''
    }
  }
}
</script>
<style  scoped>
.box-card {
  box-shadow: 0, 1px, 1px, rgba(0, 0, 0, 0.5);
}
</style>>
